<script setup lang="tsx">
import { useRouter } from 'vue-router'
import { ref, unref } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useI18n } from '@/hooks/web/useI18n'
import useSchema from './components/hooks/useSchema'
import { ActionButtonsTemplate } from '@/api/global/types'
import { CurdData, FieldEnum } from '@/api/purchase/types'
import { getListApi, delListApi, confirmApi, getFieldEnumApi } from '@/api/purchase'
import { ElMessage, ElRadio, ElMessageBox } from 'element-plus'
import { AllSchemas, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { getSelectListApi } from '@/api/operator'
import { Dialog } from '@/components/Dialog'
import { getSupplierListApi } from '@/api/supplier'
import { processingAccuracy, useEnumeratePicker } from '@/utils'
// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

defineOptions({
  name: 'PurchaseManagement'
})
type formComfirmType = {
  paid_amount?: string
  product_total_amount?: string
  id?: number
}

const { push } = useRouter()
const ids = ref<string[]>([])

const searchParams = ref({})

const isComfirmVisible = ref(false)
const formComfirm = ref<formComfirmType>({})
const formLabelWidth = '140px'

// 入库弹窗
const entryVisible = ref(false)
const entryType = ref()
const entryRow = ref<Partial<CurdData>>({})

const purchaseFieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}
const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState

    const res = await getListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()

const operatorList = ref([])

const getOperatorList = async () => {
  const res = await getSelectListApi({})
  if (res) {
    operatorList.value = res.data.list
  }
}
getOperatorList()

const supplierList = ref([])

const getSupplierList = async () => {
  const res = await getSupplierListApi({})
  supplierList.value = res.data.list
}

getSupplierList()

// Begin CRUD Template Block
// ------------------------
const delData = async (row: CurdData | null) => {
  const elTableExpose = await getElTableExpose()
  const selectedRows = row ? [row] : elTableExpose?.getSelectionRows() || []
  ids.value = selectedRows.map((v: CurdData) => v.id) || []

  if (ids.value.length === 0) {
    ElMessage.error(t('common.selectData'))
    return
  }

  // 如果是多选，检查是否有状态不等于20的数据
  if (!row && selectedRows.length > 0) {
    const invalidStatusRows = selectedRows.filter((item: CurdData) => item.status !== '20')
    if (invalidStatusRows.length > 0) {
      ElMessage.error('选中数据包含禁止删除的数据')
      return
    }
  }
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const confirmData = async () => {
  const res = await confirmApi({
    id: formComfirm.value?.id
  })
  if (res) {
    isComfirmVisible.value = false
    ElMessage.success(t('confirmMessage.purchase.confirmPaymentSuccess'))
    getList()
  }
}

const confirmEntry = () => {
  push({
    path: `/purchase/purchase-order-management/entry`,
    query: { id: entryRow.value.id, futures: entryType.value }
  })
}

const action = (row: CurdData, type: string) => {
  if (type == 'entry') {
    entryVisible.value = true
    entryRow.value = row
    return
  }
  push({
    path: `/purchase/purchase-order-management/${type}`,
    query: {
      id: row.id,
      total_amount: row.total_amount,
      paid_amount: processingAccuracy(Number(row.pay_amount), 2),
      pay_amount: processingAccuracy(Number(row.gap), 2),
      pay_type: row.pay_type,
      responsible: row.owner
    }
  })
}

const handleJumpToLogistics = (row: CurdData) => {
  push({ path: `/purchase/purchase-order-management/logisticsPage`, query: { id: row.id } })
}

const actionButtonsTemplate: ActionButtonsTemplate = {
  length: 6,
  template: (data: any) => {
    return (
      <>
        {
          <BaseButton size="small" onClick={() => action(data.row, 'edit')}>
            {t('action.edit')}
          </BaseButton>
        }
        <BaseButton size="small" type="primary" onClick={() => handleJumpToLogistics(data.row)}>
          {t('purchase.logistics.logistics')}
        </BaseButton>
        {data.row.pay_status != 2 && (
          <BaseButton size="small" type="warning" onClick={() => action(data.row, 'payment')}>
            {t('purchase.payment')}
          </BaseButton>
        )}
        {data.row.status == 30 && (
          <BaseButton size="small" type="primary" onClick={() => action(data.row, 'entry')}>
            {t('purchase.entry')}
          </BaseButton>
        )}
        <BaseButton size="small" type="success" onClick={() => action(data.row, 'detail')}>
          {t('action.detail')}
        </BaseButton>
        {data.row.status == 20 && (
          <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
            {t('action.del')}
          </BaseButton>
        )}
      </>
    )
  }
}

const payStatusList = ref<any>({})
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    purchaseFieldEnum.value = res.data
    console.log(8888, purchaseFieldEnum.value)
    payStatusList.value = purchaseFieldEnum.value.pay_status
    const { crudSchemas } = useSchema(
      actionButtonsTemplate,
      supplierList,
      purchaseFieldEnum.value,
      undefined,
      undefined,
      operatorList
    )
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      searchSchema: newSchemas.searchSchema || [],
      tableColumns: newSchemas.tableColumns || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })
// End CRUD Template Block
// ------------------------

const AddAction = () => {
  push('/purchase/purchase-order-management/add')
}

const delLoading = ref(false)
const getPayStatus = (data: any) => {
  const payStatus = data.row.pay_status
  if (payStatus === null || payStatus === undefined) {
    return ''
  }

  // 尝试数字匹配和字符串匹配
  console.log(8888444, payStatusList.value)
  for (const key in payStatusList.value) {
    console.log(8888444, key)
    if (key == payStatus) {
      return payStatusList.value[key]
    }
  }

  return String(payStatus)
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('action.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('action.del') }}
      </BaseButton>
    </div>
    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.id" class="order-card">
        <template #header>
          <div class="card-header">
            {{ item.id }}
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">{{ t('purchase.sup') }}:</span>
            {{ item.supid_value }}
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.purchase_no') }}:</span>
            <span class="value">{{ item.purchase_no }}</span>
          </div>
          <!-- <div class="info-row">
            <span class="label">{{ t('purchase.sales_orderno') }}:</span>
            <span class="value">{{ item.sales_orderno }}</span>
          </div> -->
          <div class="info-row">
            <span class="label">{{ t('purchase.purchaseGoods') }}:</span>
            <div>
              <div v-for="(p, pIndex) in item.purchase_goods" :key="pIndex" class="text-right">
                <span v-if="p.code">[{{ p.code }}]</span>
                <span v-if="p.num">[{{ p.num }}]</span>
                <span v-if="p.subtotal">[{{ p.subtotal }}]</span>
                <span v-if="p.order_no">[{{ p.order_no }}]</span>
              </div>
            </div>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.order_time') }}:</span>
            <span class="value">{{ item.order_time }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.signatory') }}:</span>
            <span class="value">{{ item.signatoryid_value }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.pay_type') }}:</span>
            <span class="value">{{ item.pay_type_value }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.pay_terms') }}:</span>
            <span class="value">{{ item.pay_terms_value }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.advance_delivery_date') }}:</span>
            <span class="value">{{ item.advance_delivery_date }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.pay_num') }}:</span>
            <span class="value">{{ item.pay_num }}</span>
          </div>
          <div class="info-row">
            <span class="label">已支付金额</span>
            <span class="value">{{ item.paid_amount }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.total_amount') }}:</span>
            <span class="value">{{ item.total_amount }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.product_total_amount') }}:</span>
            <span class="value">{{ item.product_total_amount }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.other_amount') }}:</span>
            <span class="value">{{ item.other_amount }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.status') }}:</span>
            <span class="value">{{ item.status_value }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.pay_status') }}:</span>
            <span class="value">{{ getPayStatus({ row: item }) }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('purchase.owner') }}:</span>
            <span class="value">{{ item.owner_value }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('purchase.notes') }}:</span>
            <span class="value">{{ item.notes }}</span>
          </div>
          <div class="flex flex-items-center justify-end">
            <BaseButton size="small" @click="action(item, 'edit')">
              {{ t('action.edit') }}
            </BaseButton>
            <BaseButton size="small" type="primary" @click="handleJumpToLogistics(item)">
              {{ t('purchase.logistics.logistics') }}
            </BaseButton>
            <template v-if="item.pay_status != 2">
              <BaseButton size="small" type="warning" @click="action(item, 'payment')">
                {{ t('purchase.payment') }}
              </BaseButton>
            </template>
            <template v-if="item.status == 30">
              <BaseButton size="small" type="primary" @click="action(item, 'entry')">
                {{ t('purchase.entry') }}
              </BaseButton>
            </template>
            <BaseButton size="small" type="success" @click="action(item, 'detail')">
              {{ t('action.detail') }}
            </BaseButton>
            <template v-if="item.status == 20">
              <BaseButton size="small" type="danger" @click="delData(item)">
                {{ t('action.del') }}
              </BaseButton>
            </template>
          </div>
        </div>
      </el-card>
      <!--    分页-->
      <Pagination
        class="mobile-table"
        :total="total"
        v-model:page="currentPage"
        v-model:limit="pageSize"
        @pagination="tableRegister"
      />
    </div>
    <template v-else>
      <Table
        showAction
        v-model:pageSize="pageSize"
        v-model:currentPage="currentPage"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        :pagination="{
          total: total
        }"
        @register="tableRegister"
      />
    </template>

    <Dialog
      v-model="isComfirmVisible"
      title="确认付款信息"
      :width="isMobile ? '100%' : '30%'"
      max-height="300px"
    >
      <div class="my-header">
        <el-form :model="formComfirm">
          <el-form-item label="采购全部金额" :label-width="formLabelWidth">
            <el-input v-model="formComfirm.paid_amount" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="已支付金额" :label-width="formLabelWidth">
            <el-input v-model="formComfirm.product_total_amount" autocomplete="off" disabled />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isComfirmVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmData"> Confirm</el-button>
        </div>
      </template>
    </Dialog>

    <Dialog
      v-model="entryVisible"
      title="确认入库类型"
      :width="isMobile ? '100%' : '30%'"
      max-height="300"
    >
      <div>
        <el-radio-group v-model="entryType" class="flex flex-col !items-start">
          <el-radio :label="0" size="large">现货</el-radio>
          <el-radio :label="1" size="large">在途期货</el-radio>
          <el-radio :label="2" size="large">大期货</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="entryVisible = false">{{ t('confirmMessage.cancel') }}</el-button>
          <el-button type="primary" @click="confirmEntry"> {{ t('confirmMessage.ok') }}</el-button>
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
